package com.linkhub.oms.admin.modules.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Lists;
import com.linkhub.oms.admin.common.exception.ExceptionFactory;
import com.linkhub.oms.admin.common.util.I18nMessageUtil;
import com.linkhub.oms.admin.modules.logistic.domain.dto.ShippingChannelDTO;
import com.linkhub.oms.admin.modules.logistic.freighttemplate.domain.dto.LogisticFreightCalculateDTO;
import com.linkhub.oms.admin.modules.logistic.freighttemplate.domain.vo.LogisticFreightCalculateVO;
import com.linkhub.oms.admin.modules.logistic.freighttemplate.service.LogisticFreightBsService;
import com.linkhub.oms.admin.modules.logistic.rules.LogisticChannelRuleManager;
import com.linkhub.oms.admin.modules.logistic.service.LogisticChannelBizService;
import com.linkhub.oms.admin.modules.order.domain.param.BaseSingleOrderParam;
import com.linkhub.oms.admin.modules.order.domain.param.OrderBizStatusChangeParam;
import com.linkhub.oms.admin.modules.order.domain.param.OrderLogisticParam;
import com.linkhub.oms.admin.modules.order.domain.vo.LogisticFreightVO;
import com.linkhub.oms.admin.modules.order.domain.vo.OrderLogisticVO;
import com.linkhub.oms.admin.modules.order.service.OrderBizService;
import com.linkhub.oms.admin.modules.order.service.OrderInfoAssembleService;
import com.linkhub.oms.admin.modules.product.service.LocalProductCalculateService;
import com.linkhub.oms.admin.modules.stock.domain.dto.PreemptionDTO;
import com.linkhub.oms.admin.modules.stock.exception.PreemptionFailException;
import com.linkhub.oms.admin.modules.stock.service.StockHandler;
import com.linkhub.oms.admin.modules.user.accountflow.service.IUserAccountFlowBizService;
import com.linkhub.oms.common.constant.SymbolConstant;
import com.linkhub.oms.common.constant.WmsInfoConstant;
import com.linkhub.oms.common.enums.IEnumConvert;
import com.linkhub.oms.common.enums.mp.*;
import com.linkhub.oms.common.exception.BizException;
import com.linkhub.oms.common.util.QtBeanUtil;
import com.linkhub.oms.common.util.QtBigDecimalUtil;
import com.linkhub.oms.common.util.QtStreamUtil;
import com.linkhub.oms.common.util.WmsUtil;
import com.linkhub.oms.common.util.json.QtFastjsonUtil;
import com.linkhub.oms.component.mp.util.QtMpUpdateAssist;
import com.linkhub.oms.dao.mpservice.*;
import com.linkhub.oms.data.sync.api.shopify.domain.response.ShopOrderResponse;
import com.linkhub.oms.data.sync.api.wms.domain.dto.WmsEntryOrderBatchCreateDTO;
import com.linkhub.oms.data.sync.api.wms.domain.dto.WmsStockOutBatchCreateDTO;
import com.linkhub.oms.data.sync.api.wms.domain.response.EntryOrderBatchCreateResponse;
import com.linkhub.oms.data.sync.api.yunexpress.domain.request.InterceptRequest;
import com.linkhub.oms.data.sync.api.yunexpress.domain.request.PriceTrialRequest;
import com.linkhub.oms.data.sync.api.yunexpress.domain.response.InterceptResponse;
import com.linkhub.oms.data.sync.api.yunexpress.domain.response.PriceTrialResponse;
import com.linkhub.oms.data.sync.service.OMSYunExpressApiService;
import com.linkhub.oms.data.sync.service.ShopifyApiService;
import com.linkhub.oms.data.sync.service.WMSApiService;
import com.linkhub.oms.entity.*;
import com.linkhub.oms.entity.resulttype.order.OrderInfoDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: OrderBizService
 * @Author: echo
 * @Date: 2024/4/3 15:33
 * @Version: 1.0
 */
@Slf4j
@Service
public class OrderBizServiceImpl implements OrderBizService {

    @Resource
    private IOrderService orderService;
    @Resource
    private IOrderAddressService orderAddressService;
    @Resource
    private IOrderProductService orderProductService;
    @Resource
    private IPickUpGoodsOrderService pickUpGoodsOrderService;
    @Resource
    private IEntryOrderLineService entryOrderLineService;
    @Resource
    private IOrderOriginBusinessStatusService orderOriginBusinessStatusService;
    @Resource
    private ILocalProductService localProductService;
    @Resource
    private LogisticChannelBizService logisticChannelBizService;
    @Resource
    private OrderInfoAssembleService orderInfoAssembleService;
    @Resource
    private LocalProductCalculateService localProductCalculateService;
    @Resource
    private OMSYunExpressApiService omsYunExpressApiService;
    @Resource
    private LogisticChannelRuleManager logisticChannelRuleManager;
    @Resource
    private StockHandler stockHandler;
    @Resource
    private LogisticFreightBsService logisticFreightBsService;
    @Resource
    private IShopService shopService;
    @Resource
    private ShopifyApiService shopifyApiService;
    @Resource
    private WMSApiService wmsApiService;
    @Resource
    private IShopProductSkuMappingService shopProductSkuMappingService;
    @Resource
    private IUserAccountFlowBizService userAccountFlowBizService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeBizState( OrderBizStatusChangeParam bizStatusChangeParam ) {

        if (bizStatusChangeParam.isCustomerRole()) {
            changeCustomerBizState(bizStatusChangeParam);
            // 进入待处理

        } else {
            changeEmployeeBizState(bizStatusChangeParam);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchOrders( List<OrderEntity> orders ) {
        if (CollUtil.isEmpty(orders)) {
            return;
        }

        List<OrderAddressEntity> orderAddressList = QtStreamUtil.filterAndMap(orders,
                order -> Objects.nonNull(order.getOrderAddress()),
                OrderEntity::getOrderAddress);

        List<OrderProductEntity> orderProducts = QtStreamUtil.filterAndFlatMap(orders,
                order -> CollUtil.isNotEmpty(order.getOrderLineItems()),
                order -> order.getOrderLineItems().stream());

        QtStreamUtil.peek(orders, order -> order.setId(null));
        QtStreamUtil.peek(orderAddressList, address -> address.setId(null));
        QtStreamUtil.peek(orderProducts, product -> product.setId(null));

        orderService.saveBatch(orders);
        orderProductService.saveBatch(orderProducts);
        orderAddressService.saveBatch(orderAddressList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrders( List<String> orderIds ) {
        orderService.deleteByOrderIds(orderIds);
        orderProductService.deleteBySysOrderIds(orderIds);
        orderAddressService.deleteBySysOrderIds(orderIds);
    }

    @Override
    public void saveEntryOrders( PickUpGoodsOrderEntity pickUpGoodsOrder ) {
        List<EntryOrderLineEntity> entryOrderLines = pickUpGoodsOrder.getOrderLines();
        String sysEntryOrderCode = pickUpGoodsOrder.getSysEntryOrderCode();
        pickUpGoodsOrder.setId(null);
        QtStreamUtil.peek(entryOrderLines, orderLines -> orderLines.setId(null));

        pickUpGoodsOrderService.save(pickUpGoodsOrder);

        entryOrderLineService.deleteByEntryOrderCode(sysEntryOrderCode);
        entryOrderLineService.saveBatch(entryOrderLines);

    }

    @Override
    public void updateEntryOrders( PickUpGoodsOrderEntity pickUpGoodsOrder ) {
        List<EntryOrderLineEntity> entryOrderLines = pickUpGoodsOrder.getOrderLines();
        String sysEntryOrderCode = pickUpGoodsOrder.getSysEntryOrderCode();
        QtStreamUtil.peek(entryOrderLines, orderLines -> orderLines.setId(null));

        QtMpUpdateAssist.updateByIdWithSetNull(pickUpGoodsOrder, pickUpGoodsOrderService, PickUpGoodsOrderEntity::getId);

        entryOrderLineService.deleteByEntryOrderCode(sysEntryOrderCode);
        entryOrderLineService.saveBatch(entryOrderLines);
    }

    @Override
    public List<OrderLogisticVO> listOrderLogistics( String sysOrderId ) {
        OrderInfoDO orderInfoDO = orderInfoAssembleService.assembleOrder(sysOrderId);
        OrderEntity order = orderInfoDO.getOrder();
        List<ShippingChannelDTO> channels = logisticChannelBizService.listShopShippingChannels(order.getSysShopId(), order.getShippingMethod());
        if (CollUtil.isEmpty(channels)) {
            return Lists.newArrayListWithCapacity(0);
        }

        List<ShippingChannelDTO> res = logisticChannelRuleManager.matchAll(channels, sysOrderId);
        return QtBeanUtil.copyList(res, OrderLogisticVO::new);

    }

    @Override
    public LogisticFreightVO queryLogisticFreight( String sysOrderId, String channelCode ) {
        // 查询订单地址获取简码
        OrderAddressEntity orderAddress = orderAddressService.getByOrderIds(sysOrderId);
        if (Objects.isNull(orderAddress) || StringUtils.isBlank(orderAddress.getCountryCode())) {
            return LogisticFreightVO.empty();
        }

        LogisticFreightCalculateDTO logisticFreightCalculateDTO = localProductCalculateService.calculateOrderWeightAndVolume(sysOrderId);
        logisticFreightCalculateDTO.setCountryCode(orderAddress.getCountryCode());
        logisticFreightCalculateDTO.setChannelCode(channelCode);
        logisticFreightCalculateDTO.setPostCode(orderAddress.getZip());

        // 计算运费
        LogisticFreightCalculateVO logisticFreightCalculateVO = logisticFreightBsService.calculateFreight(logisticFreightCalculateDTO);
        LogisticFreightVO logisticFreightVO = new LogisticFreightVO();
        logisticFreightVO.setEstimatedFreight(QtBigDecimalUtil.toString(logisticFreightCalculateVO.getExternalFreight(), StringUtils.EMPTY));
        logisticFreightVO.setRegistrationFreight(QtBigDecimalUtil.toString(logisticFreightCalculateVO.getExternalRegistrationFee(), StringUtils.EMPTY));

        return logisticFreightVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LogisticFreightVO queryLogisticFreightByPackage( String sysOrderId, BigDecimal packageWeight, BigDecimal packageVolume) {
        OrderEntity order = orderService.getByOrderId(sysOrderId);
        if(order==null || StringUtils.isBlank(order.getChannelCode())){
            return LogisticFreightVO.empty();
        }
        String channelCode = order.getChannelCode();
        // 查询订单地址获取简码
        OrderAddressEntity orderAddress = orderAddressService.getByOrderIds(sysOrderId);
        if (Objects.isNull(orderAddress) || StringUtils.isBlank(orderAddress.getCountryCode())) {
            return LogisticFreightVO.empty();
        }

        LogisticFreightCalculateDTO logisticFreightCalculateDTO = new LogisticFreightCalculateDTO();
        logisticFreightCalculateDTO.setCountryCode(orderAddress.getCountryCode());
        logisticFreightCalculateDTO.setChannelCode(channelCode);
        logisticFreightCalculateDTO.setPostCode(orderAddress.getZip());
        logisticFreightCalculateDTO.setPackageWeight(packageWeight);
        logisticFreightCalculateDTO.setVolumeWeight(packageVolume);
        logisticFreightCalculateDTO.setDynamicWeight(BigDecimal.ZERO);

        // 计算运费
        LogisticFreightCalculateVO logisticFreightCalculateVO = logisticFreightBsService.calculateFreight(logisticFreightCalculateDTO);
        LogisticFreightVO logisticFreightVO = new LogisticFreightVO();
        logisticFreightVO.setEstimatedFreight(QtBigDecimalUtil.toString(logisticFreightCalculateVO.getExternalFreight(), StringUtils.EMPTY));
        logisticFreightVO.setRegistrationFreight(QtBigDecimalUtil.toString(logisticFreightCalculateVO.getExternalRegistrationFee(), StringUtils.EMPTY));

        // 更新入库
        OrderLogisticParam logisticParam = new OrderLogisticParam();
        logisticParam.setChannelCode(channelCode);
        logisticParam.setEstimatedFreight(logisticFreightVO.getEstimatedFreight());
        logisticParam.setRegistrationFreight(logisticFreightVO.getRegistrationFreight());
        logisticParam.setSysOrderId(Lists.newArrayList(sysOrderId));
        updateOrderLogistic(logisticParam);
        return logisticFreightVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderLogistic( OrderLogisticParam logisticParam ) {
        OrderEntity order = new OrderEntity();
        order.setChannelCode(logisticParam.getChannelCode());
        order.setEstimatedFreight(QtMpUpdateAssist.convertNumForUpdate(logisticParam.getEstimatedFreight()));
        order.setRegistrationFreight(QtMpUpdateAssist.convertNumForUpdate(logisticParam.getRegistrationFreight()));

        QtMpUpdateAssist.updateWithSetNull(order, orderService,
                wrapper -> wrapper.in(OrderEntity::getSysOrderId, logisticParam.getSysOrderId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetOrderLogistic( String sysOrderId ) {
        this.updateOrderLogistic(OrderLogisticParam.createResetParam(sysOrderId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetOrderLogistics( List<String> sysOrderIds ) {
        this.updateOrderLogistic(OrderLogisticParam.createResetParam(sysOrderIds));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoMatchOrderLogistic( String sysOrderId ) {
        List<OrderLogisticVO> logistics = this.listOrderLogistics(sysOrderId);
        if (CollUtil.isEmpty(logistics)) {
            return;
        }
        OrderLogisticVO logistic = logistics.get(0);
        String channelCode = logistic.getChannelCode();
        LogisticFreightVO logisticFreightVO = this.queryLogisticFreight(sysOrderId, channelCode);

        OrderLogisticParam logisticParam = new OrderLogisticParam();
        logisticParam.setChannelCode(channelCode);
        logisticParam.setEstimatedFreight(logisticFreightVO.getEstimatedFreight());
        logisticParam.setRegistrationFreight(logisticFreightVO.getRegistrationFreight());
        logisticParam.setSysOrderId(Lists.newArrayList(sysOrderId));
        this.updateOrderLogistic(logisticParam);
    }

    private void changeCustomerBizState( OrderBizStatusChangeParam bizStatusChangeParam ) {

        CustomerBusinessStatusEnum curBizStatus = IEnumConvert.valueOf(bizStatusChangeParam.getCurBizStatus(), CustomerBusinessStatusEnum.class);

        if (Objects.isNull(curBizStatus)) {
            throw ExceptionFactory.getI18nBizException("validation.order.curBizStatus.range");
        }
        List<BaseSingleOrderParam> shopOrders = bizStatusChangeParam.getShopOrders();
        List<String> sysOrderIds = QtStreamUtil.mapAndDistinct(shopOrders, BaseSingleOrderParam::getSysOrderId);
        List<String> sysShopIds = QtStreamUtil.mapAndDistinct(shopOrders, BaseSingleOrderParam::getSysShopId);

        if (Objects.equals(curBizStatus, CustomerBusinessStatusEnum.ON_HOLD)) {
            // 还原订单不会传changeBizStatus，需后端补充
            if (sysOrderIds.size() > 1) {
                throw ExceptionFactory.getI18nBizException("validation.multi.order.restore.changeBizStatus.not.allow");
            }
            OrderOriginBusinessStatusEntity orderOriginBusinessStatusEntity = orderOriginBusinessStatusService.getOriginStatus(sysOrderIds.get(0));
            if (Objects.isNull(orderOriginBusinessStatusEntity)) {
                throw ExceptionFactory.getI18nBizException("validation.order.restore.changeBizStatus.already");
            }
            bizStatusChangeParam.setChangeBizStatus(orderOriginBusinessStatusEntity.getOriginCustomerBusinessStatus());
            orderOriginBusinessStatusService.deleteOriginStatusRecord(sysOrderIds.get(0));
        }

        if (Objects.isNull(bizStatusChangeParam.getChangeBizStatus())) {
            throw ExceptionFactory.getI18nBizException("validation.order.changeBizStatus.notNull");
        }
        CustomerBusinessStatusEnum changeBizStatus = IEnumConvert.valueOf(bizStatusChangeParam.getChangeBizStatus(), CustomerBusinessStatusEnum.class);

        if (Objects.isNull(changeBizStatus)) {
            throw ExceptionFactory.getI18nBizException("validation.order.changeBizStatus.range");
        }

        orderService.updateCustomerBizState(sysShopIds, sysOrderIds, curBizStatus, changeBizStatus);

        if (Objects.equals(changeBizStatus, CustomerBusinessStatusEnum.ON_HOLD)) {
            // 搁置订单保存搁置前的业务状态
            orderOriginBusinessStatusService.saveOriginStatusRecord(sysOrderIds.get(0), curBizStatus.getCode());
        }

        if (Objects.equals(changeBizStatus, CustomerBusinessStatusEnum.PENDING_PROCESSED)) {
            List<OrderEntity> orderEntityList = orderService.listBySysOrderIds(sysOrderIds);
            List<String> notHasChannelCodeOrders = orderEntityList.stream()
                    .filter(order -> StringUtils.isBlank(order.getChannelCode()))
                    .map(OrderEntity::getSysOrderId)
                    .collect(Collectors.toList());
            notHasChannelCodeOrders.forEach(this::autoMatchOrderLogistic);
        }

        if (Objects.equals(changeBizStatus, CustomerBusinessStatusEnum.VOID)) {
            // 取消库存预占

            Map<String, List<OrderProductEntity>> orderLocalSkuMap = orderInfoAssembleService
                    .queryOrderLocalSkuIds(QtStreamUtil.map(bizStatusChangeParam.getShopOrders(), BaseSingleOrderParam::getSysOrderId));
            orderLocalSkuMap.forEach(( orderId, orderProducts ) -> {
                List<PreemptionDTO> preemptionDTOS = Lists.newArrayListWithCapacity(orderProducts.size());
                for (OrderProductEntity orderProduct : orderProducts) {
                    PreemptionDTO preemptionDTO = new PreemptionDTO();
                    preemptionDTO.setUserId(bizStatusChangeParam.getUserId());
                    preemptionDTO.setStashName(WmsInfoConstant.WAREHOUSE_CODE);
                    preemptionDTO.setSkuId(orderProduct.getSkuId());
                    preemptionDTO.setSkuQuantity(orderProduct.getCurrentQuantity());
                    preemptionDTO.setBusinessType(WmsInfoConstant.XSDD);
                    preemptionDTO.setBusinessNo(orderProduct.getSysOrderId());
                    preemptionDTOS.add(preemptionDTO);
                }
                try {
                    stockHandler.orderCancel(preemptionDTOS);
                } catch (PreemptionFailException e) {
                    throw ExceptionFactory.getI18nBizException("stock.preemption.cancel.fail");
                }
            });
        }

    }

    private void changeEmployeeBizState( OrderBizStatusChangeParam bizStatusChangeParam ) {
        if (Objects.isNull(bizStatusChangeParam.getChangeBizStatus())) {
            throw ExceptionFactory.getI18nBizException("validation.order.changeBizStatus.notNull");
        }

        EmployeeBusinessStatusEnum curBizStatus = IEnumConvert.valueOf(bizStatusChangeParam.getCurBizStatus(), EmployeeBusinessStatusEnum.class);
        EmployeeBusinessStatusEnum changeBizStatus = IEnumConvert.valueOf(bizStatusChangeParam.getChangeBizStatus(), EmployeeBusinessStatusEnum.class);
        if (Objects.isNull(curBizStatus)) {
            throw ExceptionFactory.getI18nBizException("validation.order.curBizStatus.range");
        }

        if (Objects.isNull(changeBizStatus)) {
            throw ExceptionFactory.getI18nBizException("validation.order.changeBizStatus.range");
        }
        List<BaseSingleOrderParam> shopOrders = bizStatusChangeParam.getShopOrders();
        List<String> sysOrderIds = QtStreamUtil.mapAndDistinct(shopOrders, BaseSingleOrderParam::getSysOrderId);
        orderService.updateEmployeeBizState(sysOrderIds, curBizStatus, changeBizStatus);

        if (Objects.equals(changeBizStatus, CustomerBusinessStatusEnum.VOID)) {
            // 取消库存预占

            Map<String, List<OrderProductEntity>> orderLocalSkuMap = orderInfoAssembleService
                    .queryOrderLocalSkuIds(QtStreamUtil.map(bizStatusChangeParam.getShopOrders(), BaseSingleOrderParam::getSysOrderId));
            orderLocalSkuMap.forEach(( orderId, orderProducts ) -> {
                List<PreemptionDTO> preemptionDTOS = Lists.newArrayListWithCapacity(orderProducts.size());
                for (OrderProductEntity orderProduct : orderProducts) {
                    PreemptionDTO preemptionDTO = new PreemptionDTO();
                    preemptionDTO.setUserId(bizStatusChangeParam.getUserId());
                    preemptionDTO.setStashName(WmsInfoConstant.WAREHOUSE_CODE);
                    preemptionDTO.setSkuId(orderProduct.getSkuId());
                    preemptionDTO.setSkuQuantity(orderProduct.getCurrentQuantity());
                    preemptionDTO.setBusinessType(WmsInfoConstant.XSDD);
                    preemptionDTO.setBusinessNo(orderProduct.getSysOrderId());
                    preemptionDTOS.add(preemptionDTO);
                }
                try {
                    stockHandler.orderCancel(preemptionDTOS);
                } catch (PreemptionFailException e) {
                    throw ExceptionFactory.getI18nBizException("stock.preemption.cancel.fail");
                }
            });
        }
    }

    @Override
    public Void interceptLogistics( String sysOrderId ) {
        // 查询系统订单ID对应的运单号
        OrderEntity orderEntity = orderService.getByOrderId(sysOrderId);
        String waybillNumber = null;
        if (orderEntity != null) {
            waybillNumber = orderEntity.getWayBillNumber();
        }

        if (StringUtils.isBlank(waybillNumber)) {
            throw ExceptionFactory.getI18nBizException("logistic.order.no.waybill.number");
        }
        // 调用云途api拦截运单
        InterceptRequest interceptRequest = new InterceptRequest();
        interceptRequest.setOrderNumber(waybillNumber);
        // 单号类型：1-云途单号,2-客户订单号,3-跟踪号
        interceptRequest.setOrderType("1");
        interceptRequest.setRemark("客户要求拦截");

        InterceptResponse response = omsYunExpressApiService.intercept(interceptRequest);

        if (response.success()) {
            WmsEntryOrderBatchCreateDTO wmsCreateWarehouseWarrantDTO = new WmsEntryOrderBatchCreateDTO();
            wmsCreateWarehouseWarrantDTO.setEntryOrderCode(orderEntity.getSysOrderId());
            wmsCreateWarehouseWarrantDTO.setOwnerCode(WmsInfoConstant.OWNER_CODE);
            wmsCreateWarehouseWarrantDTO.setWarehouseCode(WmsInfoConstant.WAREHOUSE_CODE);
            wmsCreateWarehouseWarrantDTO.setOrderType("WLTH");
            wmsCreateWarehouseWarrantDTO.setExpectStartTime(DateUtil.format(new Date(), DatePattern.UTC_SIMPLE_PATTERN));
            wmsCreateWarehouseWarrantDTO.setLogisticsName("YunExpress");
            wmsCreateWarehouseWarrantDTO.setExpressCode(orderEntity.getWayBillNumber());
            wmsCreateWarehouseWarrantDTO.setSupplierCode("0");

            final ShopEntity shopEntity = shopService.getByShopId(orderEntity.getSysShopId());
            wmsCreateWarehouseWarrantDTO.setUserDefined1(shopEntity.getUserId());

            List<OrderProductEntity> orderProductEntities1 = orderProductService.listBySysOrderId(orderEntity.getSysOrderId());
            orderProductEntities1 = orderProductEntities1.stream()
                    .peek(ord -> {
                        if (StringUtils.isBlank(ord.getSkuId())) {
                            ShopProductSkuMappingEntity byShopSkuId = shopProductSkuMappingService.getByShopSkuId(ord.getShopSkuId());
                            ord.setSkuId(byShopSkuId.getSkuId());
                        }

                    }).collect(Collectors.toList());
            List<WmsEntryOrderBatchCreateDTO.ProductParam> products = Lists.newArrayList();
            for (OrderProductEntity orderProduct : orderProductEntities1) {
                WmsEntryOrderBatchCreateDTO.ProductParam product = new WmsEntryOrderBatchCreateDTO.ProductParam();
                products.add(product);
                LocalProductEntity localProductEntity = localProductService.getBySkuId(orderProduct.getSkuId());
                product.setItemCode(WmsUtil.createItemCode(localProductEntity.getUserId(), localProductEntity.getSkuId()));
                product.setPlanQty(String.valueOf(orderProduct.getCurrentQuantity()));
            }
            wmsCreateWarehouseWarrantDTO.setProductInfo(products);
            wmsCreateWarehouseWarrantDTO.setOutBizCode(orderEntity.getSysOrderId());
            EntryOrderBatchCreateResponse entryOrderBatchCreateResponse = wmsApiService.batchCreateEntryOrder(wmsCreateWarehouseWarrantDTO);
            if (!entryOrderBatchCreateResponse.success()) {
                log.error("退货入库单创建失败，入库单信息：{}， 响应：{}",
                        QtFastjsonUtil.toJSONString(wmsCreateWarehouseWarrantDTO), QtFastjsonUtil.toJSONString(entryOrderBatchCreateResponse));
                throw ExceptionFactory.getI18nBizException("wms.create.entry.order.back.fail");
            }
            // 退款
            userAccountFlowBizService.refundOrderAccountFlowByDocumentId(orderEntity.getSysOrderId());

            OrderEntity intercept = new OrderEntity();
            intercept.setOrderStatus(OrderStatusEnum.CANCELLED);
            intercept.setCustomerBusinessStatus(CustomerBusinessStatusEnum.VOID);
            intercept.setEmployeeBusinessStatus(EmployeeBusinessStatusEnum.CANCELLED);
            orderService.updateOrderInfo(sysOrderId, intercept);
        } else {
            // 拦截失败逻辑
            throw new BizException(I18nMessageUtil.getMessage("yunexpress.intercept.failed", response.getMessage()));
        }

        return null;
    }

    @Override
    public boolean syncOrderIfNecessary( List<OrderEntity> pendingSubmitOrders ) {
        // 过滤出shopify的订单，其他平台订单不需要同步
        List<OrderEntity> filteredShopifyOrders = orderService.deepMappingOrders(pendingSubmitOrders).stream()
                .filter(order -> order.getShopInfo() != null &&
                        PlatFormEnum.SHOPIFY == order.getShopInfo().getPlatForm())
                .collect(Collectors.toList());
        if (filteredShopifyOrders.isEmpty()) {
            return false;
        }
        Map<String, List<OrderEntity>> orderGroupMap = QtStreamUtil.group(filteredShopifyOrders, OrderEntity::getSysShopId);
        Map<Long, LocalDateTime> orderUpdateTimeMap = getPlatFormOrderUpdateTime(orderGroupMap);
        boolean updateFlag = QtStreamUtil.anyMatch(filteredShopifyOrders,
                order -> CompareUtil.compare(orderUpdateTimeMap.get(order.getPlatFormOrderId()),
                        order.getUpdatedAtConvert()) > 0);
        return updateFlag;
    }

    private Map<Long, LocalDateTime> getPlatFormOrderUpdateTime( Map<String, List<OrderEntity>> orderGroupMap ) {
        List<ShopEntity> shops = shopService.listBySysShopIds(Lists.newArrayList(orderGroupMap.keySet()));
        Map<String, ShopEntity> shopMap = QtStreamUtil.toMap(shops, ShopEntity::getSysShopId);
        List<ShopOrderResponse.Orders> orders = Lists.newArrayList();
        orderGroupMap.forEach(( k, val ) -> {
            List<Long> platFormOrderIds = QtStreamUtil.map(val, OrderEntity::getPlatFormOrderId);
            ShopEntity shopEntity = shopMap.get(k);
            ShopOrderResponse orderResponse = shopifyApiService.getOrderLatestUpdateTime(shopEntity.getUrl(),
                    shopEntity.getAccessToken(),
                    platFormOrderIds);
            orders.addAll(orderResponse.getOrders());
        });

        return QtStreamUtil.toMap(orders, ShopOrderResponse.Orders::getId, ShopOrderResponse.Orders::getUpdatedTime);


    }
}
